package com.zengdada.authority.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @Auther: 12614
 * @Contact: 1261438511@qq.com
 * @Date: 2019-03-13 18:29
 * @Description:
 */
public class FileUtils {

    public static void base64toFile(String base64Code, String targetPath) throws IOException {
        base64toFile(base64Code, targetPath, false);
    }

    /**
     * 将base64字符保存文本文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */

    public static void base64toFile(String base64Code, String targetPath, boolean isDecoder) throws IOException {
        File tempFile = new File(targetPath);
        createFolder(tempFile);
        deleteExistingFile(tempFile);
        try (FileOutputStream out = new FileOutputStream(targetPath)) {
            byte[] buffer = isDecoder ? new BASE64Decoder().decodeBuffer(base64Code) : base64Code.getBytes();
            out.write(buffer);
        }
    }


    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */

    public static void decoderBase64File(String base64Code, String targetPath)
            throws IOException {
        base64toFile(base64Code, targetPath, true);
    }

    /**
     * 将文件转成base64 字符串
     *
     * @param path 文件路径
     * @return *
     * @throws Exception
     */

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        try (FileInputStream inputFile = new FileInputStream(file)) {
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            return new BASE64Encoder().encode(buffer);
        }
    }

    /**
     * 将输入流中的数据保存到文件
     *
     * @param in
     * @param targetPath
     * @throws Exception
     */
    public static void saveFile(InputStream in, String targetPath) throws Exception {
        File tempFile = new File(targetPath);
        createFolder(tempFile);
        deleteExistingFile(tempFile);
        try (FileOutputStream out = new FileOutputStream(targetPath)) {
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
        }
    }

    /**
     * 将字节数组保存到文件
     *
     * @param data
     * @param targetPath
     * @throws Exception
     */
    public static void saveFile(byte[] data, String targetPath) throws Exception {
        try (InputStream in = new ByteArrayInputStream(data)) {
            saveFile(in, targetPath);
        }
    }

    public static void obtainFile(String targetPath, OutputStream out) throws Exception {
        File file = new File(targetPath);
        if (!file.exists()) {
            throw new FileNotFoundException("文件未找到");
        }
        try (FileInputStream in = new FileInputStream(targetPath)) {
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
        }
    }

    public static byte[] obtainFile(String targetPath) throws Exception {
        try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            obtainFile(targetPath, out);
            return out.toByteArray();
        }
    }


    private static void createFolder(File file) {
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }

    private static void deleteExistingFile(File file) {
        if (file.exists()) {
            file.delete();
        }
    }


    /**
     * 删除指定文件/文件夹
     *
     * @param filePath 路径
     * @throws Exception
     */
    public static void deleteFile(String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists()) {
            return;
        }
        if (file.isFile()) {
            file.delete();
        } else {
            File[] files = file.listFiles();
            if (files == null || files.length == 0) {
                return;
            }
            for (File file1 : files) {
                String root = file1.getAbsolutePath();// 得到子文件或文件夹的绝对路径
                // System.out.println(root);
                deleteFile(root);
            }
        }
    }

    /**
     * 移动文件
     *
     * @param filePath              原文件
     * @param destinationFloderPath 目标路径
     */
    public static void moveFile(String filePath, String destinationFloderPath) {
        File file = new File(filePath);
        File destFloder = new File(destinationFloderPath);
        //检查目标路径是否合法
        if (destFloder.exists()) {
            if (destFloder.isFile()) {
                throw new RuntimeException("目标路径是个文件，请检查目标路径！");
            }
        } else {
            if (!destFloder.mkdirs()) {
                throw new RuntimeException("目标文件夹不存在，创建失败！");
            }
        }
        //检查源文件是否合法
        if (file.isFile() && file.exists()) {
            String destinationFile = destinationFloderPath + "/" + file.getName();
            if (!file.renameTo(new File(destinationFile))) {
                throw new RuntimeException("移动文件失败！");
            }
        } else {
            throw new RuntimeException("要备份的文件路径不正确，移动失败！");
        }
    }
}
